package dataStructure.xmg1.leetCode.stack;

import java.util.HashMap;
import java.util.Stack;

/**
 *
 * 20. 有效的括号
 * https://leetcode-cn.com/problems/valid-parentheses/
 *
 * @author: vince_zww
 * @date: 2020/11/28 0:46
 * @desceription:
 */
public class LeetCode_20 {

    private static HashMap<Character,Character> map = new HashMap<>();

    static {
        map.put('(', ')');
        map.put('[', ']');
        map.put('{', '}');
    }

    /**
     * [({})]
     *
     * @param s
     * @return
     */
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        int len = s.length();
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (map.containsKey(c)) {
                //入栈,如果是左字符
                stack.push(c);
            } else {
                //出栈,只有右括号
                if (stack.isEmpty()) {
                    return false;
                }
                char left = stack.pop();
                if (c != map.get(left)) {
                    return false;
                }

            }
        }
        return stack.isEmpty();
    }

    /**
     * [({})]
     *
     * @param s
     * @return
     */
    public boolean isValid1(String s) {
        Stack<Character> stack = new Stack<>();
        int len = s.length();
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (c == '(' || c == '{' || c == '[') {
                //入栈,如果是左字符
                stack.push(c);
            } else {
                //出栈,只有右括号
                if (stack.isEmpty()) {
                    return false;
                }
                char left = stack.pop();
                if (left=='(' && c!=')') return false;
                if (left=='[' && c!=']') return false;
                if (left=='{' && c!='}') return false;
            }
        }
        return stack.isEmpty();
    }
    

    /**
     * [({})]
     * @param s
     * @return
     */
    public boolean isValid2(String s) {
        while (s.contains("{}")
            || s.contains("[]")
            || s.contains("()")) {
            s = s.replace("{}", "");
            s = s.replace("()", "");
            s = s.replace("[]", "");
        }
        return s.isEmpty();
    }




}
